package com.jl.basicframework.utils.photoUtils;

import android.app.Activity;
import android.content.Context;

import com.luck.picture.lib.PictureSelectionModel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.util.List;

/***
 * @author 作者:姜澜
 * 时间:2022/3/12
 * 邮箱:316879104@pp.com
 * 类简述:调用摄像机拍摄图片
 */
public class PhotographUtils implements OnResultCallbackListener {

    private Activity mActivity;

    /**
     * 图片选择工具
     */
    private PictureSelectionModel pictureSelection;

    /**
     * 拍摄图片回调
     */
    private OnPhotographImageResult photographImageResult;

    public PhotographUtils(Activity mActivity) {
        this.mActivity = mActivity;
        initSelectionModel();
    }

    public PhotographUtils(Context context){
        this.mActivity = (Activity) context;
        initSelectionModel();
    }

    /**
     * 启动工具
     */
    public void startUtils(){
        setSelectionUtils();
    }

    /**
     * 设置图片回调
     */
    public void setPhotographImageResult(OnPhotographImageResult photographImageResult) {
        this.photographImageResult = photographImageResult;
    }

    /**
     * 初始化选择工具
     */
    private void initSelectionModel(){
        pictureSelection = PictureSelector
                .create(mActivity)
                //打开相册
                .openCamera(PictureMimeType.ofImage());

    }

    /**
     * 设置选择工具基本参数
     */
    private void setSelectionUtils(){
        //选择的类型 图片
        pictureSelection.isSingleDirectReturn(true)
                .loadImageEngine(GlideEngine.createGlideEngine())
                //大于400k进行压缩
                .compress(true)
                .minimumCompressSize(400)
                //单张拍摄
                .selectionMode(PictureConfig.SINGLE);

        pictureSelection.forResult(PictureConfig.CHOOSE_REQUEST,this);
    }


    /**
     * 拍摄图片
     * @param result 拍摄图片结果
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        if (0!=result.size()){
            //选择单张图片
            File imageFile = new File(result.get(0).getCompressPath());
            photographImageResult.onImageFile(imageFile);
        }else {
            photographImageResult.onError("未获取到拍摄图片");
        }
    }

    /**
     * 拍摄取消
     */
    @Override
    public void onCancel() {
        photographImageResult.onError("拍摄取消");
    }

    /**
     * 拍摄图片结果回调
     */
    public interface OnPhotographImageResult{

        /**
         * 图片文件回调
         * @param imageFile
         */
        void onImageFile(File imageFile);

        /**
         * 错误回调
         * @param errorMsg
         */
        void onError(String errorMsg);
    }
}
